package com.avic.rong.search.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.avic.rong.BaseActivity;
import com.avic.rong.R;
import com.avic.rong.bean.product.GoodBean;
import com.avic.rong.bean.product.SearchGroupBean;
import com.avic.rong.bean.show_bean.EsInfoBean;
import com.avic.rong.fragment.showapi.EsInfoApi;
import com.avic.rong.goodsSort.api.StandardSearchApi;
import com.avic.rong.search.adapter.homePageAdapter.SearchAllAdapter;
import com.avic.rong.userOrder.api.AddCarApi;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.DeviceUtils;
import com.avic.rong.utils.SharedPreferencesUtil;
import com.avic.rong.utils.ToastTools;
import com.avic.rong.wedgit.loadingLayout.LoadingLayout;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

public class SearchAllFragment extends Fragment implements OnLoadMoreListener, OnRefreshListener, SearchAllAdapter.CartAddListener {


    private Context mContext;
    @BindView(R.id.recycler_list)
    RecyclerView recycler_list;
    @BindView(R.id.loading_layout)
    LoadingLayout loading_layout;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    private StandardSearchApi standardSearchApi;
    private List<DelegateAdapter.Adapter> adapters = new LinkedList<>();
    private List<GoodBean> goodBeanList = new ArrayList<>();
    private List<Integer> firstPageArticleBeanIdList = new ArrayList<>();
    private SearchAllAdapter searchAllAdapter;
    public String keyword = ConstantsUtils.EMPTY_STR;

    private boolean isRefresh = false;
    private int currentPage = 1;

    public SearchAllFragment() {

    }

    public static SearchAllFragment newInstance(Context context,String keyword) {
        SearchAllFragment fragment = new SearchAllFragment();
        fragment.mContext = context;
        fragment.keyword = keyword;
        return fragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_search_all, container, false);
        ButterKnife.bind(this, view);

        searchAllAdapter = new SearchAllAdapter(mContext);
        recycler_list.setLayoutManager(new LinearLayoutManager(mContext));
        recycler_list.setAdapter(searchAllAdapter);
        searchAllAdapter.setCartAddListener(this);
        searchAllAdapter.setKeyword(keyword);

        standardSearchApi = new StandardSearchApi((BaseActivity) mContext, searchAllListener);
        standardSearchApi.setTypes(0);
        standardSearchApi.setKeyword(keyword);
        HttpManager.getInstance().doHttpDeal(standardSearchApi);
        refreshLayout.setOnLoadMoreListener(this);
        refreshLayout.setOnRefreshListener(this);


        loading_layout.hideReturnButton();
        loading_layout.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                standardSearchApi = new StandardSearchApi((BaseActivity) mContext, searchAllListener);
                standardSearchApi.setTypes(0);
                currentPage = 1;
                standardSearchApi.setPageNo(currentPage);
                HttpManager.getInstance().doHttpDeal(standardSearchApi);
            }

            @Override
            public void onReturn(View v) {

            }
        });

        return view;
    }


    //获取标准数据监听
    HttpOnNextListener<BaseResultEntity> searchAllListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {

            loading_layout.setStatus(LoadingLayout.SUCCESS);
            if (!ConstantsUtils.STATUS_SUCCESS_200.equals(subjects.getCode())) {
                ToastTools.showToast(mContext, subjects.getMsg());
                return;
            }
            List<SearchGroupBean> beans = (List<SearchGroupBean>) subjects.getData();

//            StandardItemAdapter standardItemAdapter = new StandardItemAdapter(mContext, 1);

            if (isRefresh) {
                goodBeanList.clear();
                searchAllAdapter.clearEsList();
                refreshLayout.finishRefresh();
            } else {
                refreshLayout.finishLoadMore();
            }

            //第一页特殊处理
            if (currentPage == 1) {

                if (beans.get(0).getData() != null && beans.get(0).getData().size() > 0) {
                    GoodBean goodBean1 = new GoodBean();
                    goodBean1.setTypeName("标准");
                    goodBean1.setTypeFlag(100);
                    for (int index = 0; index < beans.get(0).getData().size(); index++) {
                        beans.get(0).getData().get(index).setTypeFlag(1);
                        if (index == beans.get(0).getData().size() - 1) {
                            beans.get(0).getData().get(index).setLastOne(true);
                        }
                    }
                    goodBeanList.add(goodBean1);
                    goodBeanList.addAll(beans.get(0).getData());
                }


                if (beans.get(1).getData() != null && beans.get(1).getData().size() > 0) {
                    GoodBean goodBean2 = new GoodBean();
                    goodBean2.setTypeName("商品");
                    goodBean2.setTypeFlag(100);
                    for (int index = 0; index < beans.get(1).getData().size(); index++) {
                        beans.get(1).getData().get(index).setTypeFlag(2);
                        if (index == beans.get(1).getData().size() - 1) {
                            beans.get(1).getData().get(index).setLastOne(true);
                        }
                    }
                    goodBeanList.add(goodBean2);
                    goodBeanList.addAll(beans.get(1).getData());
                }


                if (beans.get(2).getData() != null && beans.get(2).getData().size() > 0) {
                    GoodBean goodBean3 = new GoodBean();
                    goodBean3.setTypeName("培训");
                    goodBean3.setTypeFlag(100);

                    for (int index = 0; index < beans.get(2).getData().size(); index++) {
                        beans.get(2).getData().get(index).setTypeFlag(3);
                        if (index == beans.get(2).getData().size() - 1) {
                            beans.get(2).getData().get(index).setLastOne(true);
                        }
                    }
                    goodBeanList.add(goodBean3);
                    goodBeanList.addAll(beans.get(2).getData());
                }

            }


            //文章
            if (beans.get(3).getData() != null && beans.get(3).getData().size() > 0) {
                for (int index = 0; index < beans.get(3).getData().size(); index++) {
                    beans.get(3).getData().get(index).setTypeFlag(4);
                    if (index == beans.get(3).getData().size() - 1) {
                        beans.get(3).getData().get(index).setLastOne(true);
                    }
                }

                if (currentPage == 1) {//保存第一页的文章ID,第二次请求要减去
                    goodBeanList.addAll(beans.get(3).getData());
                    for (GoodBean bean : beans.get(3).getData()) {
                        firstPageArticleBeanIdList.add(bean.getDataId());
                    }
                } else if (currentPage == 2) {
                    List<GoodBean> tempBeanList = beans.get(3).getData();
                    List<GoodBean> filterdBeanList = new ArrayList<>();

                    for (GoodBean bean : tempBeanList) {
                        if (!firstPageArticleBeanIdList.contains(bean.getDataId())) {
                            filterdBeanList.add(bean);
                        }
                    }
                } else {
                    goodBeanList.addAll(beans.get(3).getData());
                }

                String countId = "";
                for (int i = 0; i < beans.get(3).getData().size(); i++) {
                    int dataId = beans.get(3).getData().get(i).getDataId();
                    countId += dataId + ",";
                }
                if (!TextUtils.isEmpty(countId)) {
                    countId = countId.substring(0, countId.length() - 1);
                    EsInfoApi esInfoApi = new EsInfoApi((RxAppCompatActivity) getActivity(), ensOnNextListener, countId);
                    esInfoApi.setCache(false);
                    HttpManager.getInstance().doHttpDeal(esInfoApi);
                }
            }

            searchAllAdapter.setBeanList(goodBeanList);

//            LinearLayoutHelper layoutHelper12 = new LinearLayoutHelper();
//            layoutHelper12.setBgColor(Color.YELLOW);
////            layoutHelper12.setAspectRatio(2.0f);
//            List<String> titleList = new ArrayList<>();
//            titleList.add("标准");
//            adapters.add(new VTitleAdapter(mContext, layoutHelper12, titleList));
//
//
//            LinearLayoutHelper layoutHelper1 = new LinearLayoutHelper();
//            layoutHelper1.setBgColor(Color.YELLOW);
////            layoutHelper1.setAspectRatio(2.0f);
////            layoutHelper1.setMargin(10, 10, 10, 10);
////            layoutHelper1.setPadding(10, 10, 10, 10);
//
//            VStandardAdapter vStandardAdapter = new VStandardAdapter(mContext, layoutHelper1, goodBeanList);
//            adapters.add(vStandardAdapter);
//
//
//
//
//            LinearLayoutHelper layoutHelper124 = new LinearLayoutHelper();
//            layoutHelper124.setBgColor(Color.YELLOW);
////            layoutHelper12.setAspectRatio(2.0f);
//            List<String> titleList2 = new ArrayList<>();
//            titleList2.add("商品");
//            adapters.add(new VTitleAdapter(mContext, layoutHelper124, titleList2));
//
//            LinearLayoutHelper layoutHelper13 = new LinearLayoutHelper();
//            layoutHelper13.setBgColor(Color.YELLOW);
////            layoutHelper13.setAspectRatio(2.0f);
////            layoutHelper13.setMargin(10, 10, 10, 10);
////            layoutHelper13.setPadding(10, 10, 10, 10);
//
//            VBookAdapter vStandardAdapter3 = new VBookAdapter(mContext, layoutHelper13, beans.get(1).getData());
//            adapters.add(vStandardAdapter3);
//
//            //培训
//            LinearLayoutHelper layoutHelper1245 = new LinearLayoutHelper();
//            layoutHelper1245.setBgColor(Color.YELLOW);
////            layoutHelper12.setAspectRatio(2.0f);
//            List<String> titleList24 = new ArrayList<>();
//            titleList24.add("培训");
//            adapters.add(new VTitleAdapter(mContext, layoutHelper124, titleList24));
//
//
//            VCultivateAdapter vCultivateAdapter = new VCultivateAdapter(mContext, layoutHelper13, beans.get(2).getData());
//            adapters.add(vCultivateAdapter);
//
//
//            //文章
//            LinearLayoutHelper layoutHelper12456 = new LinearLayoutHelper();
//            layoutHelper12456.setBgColor(Color.YELLOW);
////            layoutHelper12.setAspectRatio(2.0f);
//            List<String> layoutHelper124565 = new ArrayList<>();
//            layoutHelper124565.add("文章");
//            adapters.add(new VTitleAdapter(mContext, layoutHelper124, layoutHelper124565));
//
//            VArticleAdapter vArticleAdapter = new VArticleAdapter(mContext, layoutHelper13, beans.get(3).getData());
//            adapters.add(vArticleAdapter);
//
//
//            delegateAdapter.setAdapters(adapters);


//            if (isRefresh) {
//                goodBeanList.clear();
//            }

//            goodBeanList.addAll(beans.get(0).getData());


//            if (isRefresh) {
//                refreshLayout.finishRefresh();
//            } else {
//                refreshLayout.finishLoadMore();
//            }
//
//            if (goodBeanList.size() == 0) {
//                loading_layout.setStatus(LoadingLayout.EMPTY);
//            } else {
//                loading_layout.setStatus(LoadingLayout.SUCCESS);
//            }

//            standardItemAdapter.setBeanList(goodBeanList);
        }


        @Override
        public void onError(final Throwable e) {
            if (isRefresh) {
                refreshLayout.finishRefresh();
            } else {
                refreshLayout.finishLoadMore();
            }
            if (e instanceof SocketTimeoutException || e instanceof ConnectException) {
                loading_layout.setStatus(LoadingLayout.NO_NETWORK);
            } else {
                loading_layout.setStatus(LoadingLayout.ERROR);
            }
        }
    };


    //搜索补全接口
    HttpOnNextListener<BaseResultEntity> ensOnNextListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            if (ConstantsUtils.STATUS_SUCCESS_200.equals(baseResultEntity.getCode())) {
                List<EsInfoBean> esInfoBean = (ArrayList<EsInfoBean>) baseResultEntity.getData();
                searchAllAdapter.addEsList(esInfoBean);
                searchAllAdapter.notifyDataSetChanged();
            } else {
                Toast.makeText(getActivity(), "没有数据", Toast.LENGTH_SHORT).show();
            }
        }
    };


    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        isRefresh = false;
        currentPage = currentPage + 1;
        if (currentPage > 1) {
            standardSearchApi.setTypes(5);//第二页只获取文章
            currentPage = 1;
        }
        standardSearchApi.setPageNo(currentPage);
        HttpManager.getInstance().doHttpDeal(standardSearchApi);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        isRefresh = true;
        currentPage = 1;
        standardSearchApi.setPageNo(currentPage);
        standardSearchApi.setTypes(0);
        HttpManager.getInstance().doHttpDeal(standardSearchApi);
    }

    //添加购物车
    @Override
    public void addCar(int skuId, ImageView cartImageView) {
        Map<String, String> map = new HashMap<>();
        String skuStr = "{" + "\"" + skuId + "\"" + ":" + "1}";
        map.put("skuStr", skuStr);
        map.put("orderType", "4");
        map.put("buyAgain", "0");//是否再次购买（0/1）
        map.put("token", SharedPreferencesUtil.getLoginToken());
        map.put("deviceId", DeviceUtils.getIMEString(mContext));
        AddCarApi addCarApi = new AddCarApi((BaseActivity) mContext, new AddCarOnNextListener(cartImageView));
        addCarApi.setCache(false);
        addCarApi.setMap(map);
        HttpManager.getInstance().doHttpDeal(addCarApi);
    }


    class AddCarOnNextListener extends HttpOnNextListener<BaseResultEntity> {

        ImageView cartImageView;

        public AddCarOnNextListener(ImageView cartImg) {
            this.cartImageView = cartImg;
        }

        @Override
        public void onNext(BaseResultEntity subjects) {
            if (!ConstantsUtils.STATUS_SUCCESS_0000.equals(subjects.getCode())) {
                ToastTools.showToast(mContext, subjects.getMsg());
                return;
            }
            ToastTools.showToast("添加成功!");
        }

        @Override
        public void onError(final Throwable e) {
            ToastTools.showToast(mContext, e.getMessage());
        }
    }


    private void initData() {
//        StickyLayoutHelper layoutHelper = new StickyLayoutHelper();
//        //layoutHelper.setOffset(100);
//        layoutHelper.setAspectRatio(4);
//        adapters.add(new SubAdapter(mContext, layoutHelper, 1, new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 50)));
//
//
//        LinearLayoutHelper layoutHelper1 = new LinearLayoutHelper();
//        layoutHelper1.setBgColor(Color.YELLOW);
//        layoutHelper1.setAspectRatio(2.0f);
//        layoutHelper1.setMargin(10, 10, 10, 10);
//        layoutHelper1.setPadding(10, 10, 10, 10);
//        adapters.add(new SubAdapter(mContext, layoutHelper1, 10) {
//            @Override
//            public void onBindViewHolder(final MainViewHolder holder, int position) {
//                super.onBindViewHolder(holder, position);
//                final SubAdapter subAdapter = this;
//                //mainHandler.postDelayed(new Runnable() {
//                //    @Override
//                //    public void run() {
//                //        //delegateAdapter.removeAdapter(subAdapter);
//                //        //notifyItemRemoved(1);
//                //        holder.itemView.setVisibility(View.GONE);
//                //        notifyItemChanged(1);
//                //        layoutManager.runAdjustLayout();
//                //    }
//                //}, 2000L);
//            }
//        });
//
//        StickyLayoutHelper layoutHelper2 = new StickyLayoutHelper();
//        //layoutHelper.setOffset(100);
//        layoutHelper2.setAspectRatio(4);
//        adapters.add(new SubAdapter(mContext, layoutHelper2, 1, new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 50)));
//
//        LinearLayoutHelper layoutHelper12 = new LinearLayoutHelper();
//        layoutHelper12.setBgColor(Color.YELLOW);
//        layoutHelper12.setAspectRatio(2.0f);
//        layoutHelper12.setMargin(10, 10, 10, 10);
//        layoutHelper12.setPadding(10, 10, 10, 10);
//        adapters.add(new SubAdapter(mContext, layoutHelper12, 10) {
//            @Override
//            public void onBindViewHolder(final MainViewHolder holder, int position) {
//                super.onBindViewHolder(holder, position);
//                final SubAdapter subAdapter = this;
//                //mainHandler.postDelayed(new Runnable() {
//                //    @Override
//                //    public void run() {
//                //        //delegateAdapter.removeAdapter(subAdapter);
//                //        //notifyItemRemoved(1);
//                //        holder.itemView.setVisibility(View.GONE);
//                //        notifyItemChanged(1);
//                //        layoutManager.runAdjustLayout();
//                //    }
//                //}, 2000L);
//            }
//        });
    }


//    static class SubAdapter extends DelegateAdapter.Adapter<MainViewHolder> {
//
//        private Context mContext;
//
//        private LayoutHelper mLayoutHelper;
//
//
//        private LayoutParams mLayoutParams;
//        private int mCount = 0;
//
//
//        public SubAdapter(Context context, LayoutHelper layoutHelper, int count) {
//            this(context, layoutHelper, count, new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//        }
//
//        public SubAdapter(Context context, LayoutHelper layoutHelper, int count, @NonNull LayoutParams layoutParams) {
//            this.mContext = context;
//            this.mLayoutHelper = layoutHelper;
//            this.mCount = count;
//            this.mLayoutParams = layoutParams;
//        }
//
//        @Override
//        public LayoutHelper onCreateLayoutHelper() {
//            return mLayoutHelper;
//        }
//
//        @Override
//        public MainViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//            return new MainViewHolder(LayoutInflater.from(mContext).inflate(R.layout.item, parent, false));
//        }
//
//        @Override
//        public void onBindViewHolder(MainViewHolder holder, int position) {
//            // only vertical
//            holder.itemView.setLayoutParams(new LayoutParams(mLayoutParams));
//        }
//
//
//        @Override
//        protected void onBindViewHolderWithOffset(MainViewHolder holder, int position, int offsetTotal) {
//            ((TextView) holder.itemView.findViewById(R.id.title)).setText(Integer.toString(offsetTotal));
//        }
//
//        @Override
//        public int getItemCount() {
//            return mCount;
//        }
//    }
//
//    static class MainViewHolder extends RecyclerView.ViewHolder {
//
//        public static volatile int existing = 0;
//        public static int createdTimes = 0;
//
//        public MainViewHolder(View itemView) {
//            super(itemView);
//            createdTimes++;
//            existing++;
//        }
//
//        @Override
//        protected void finalize() throws Throwable {
//            existing--;
//            super.finalize();
//        }
//    }


}
